package com.fwj.core.common.annotation;
import org.apache.commons.lang.StringUtils;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;

/**
 * @Author: fwj
 * @Data: 2022/4/9 22:51
 * @Version 1.0
 * @Description:
 */

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.PARAMETER,ElementType.METHOD})
@Constraint(validatedBy = CommonValidate.CommonValidator.class)
public @interface CommonValidate {

    String message() default "参数校验失败";

    String[] value() default {};

    boolean notNull() default false;

    String regEX() default "";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    //具体校验类
    class CommonValidator implements ConstraintValidator<CommonValidate,String> {

        private String[] value;
        private String message;
        private String regEx;
        private boolean notNull;

        @Override
        public void initialize(CommonValidate commonValidate) {
            this.value = commonValidate.value();
            this.notNull = commonValidate.notNull();
            this.regEx = commonValidate.regEX();
            this.message = commonValidate.message();
        }

        @Override
        public boolean isValid(String str, ConstraintValidatorContext context) {
            try {
                return (    ( null == this.value ? true : validateValue() )
                        &&  ( false == this.notNull ? true : validateNotNull(str) )
                        &&  ( StringUtils.isNotEmpty(this.regEx) ? true : validateRegEx(str) )
                );
            } catch (Exception e){
                return false;
            }
        }

        private boolean validateValue(){
            return true;
        }

        private boolean validateNotNull(String str){
            boolean res;
            if (res = (false == StringUtils.isNotBlank(str))) {
                this.message = "参数校验失败,缺少必填参数";
            }
            return !res;
        }

        private boolean validateRegEx(String str){
            return str.matches(this.regEx);
        }

    }
}
